﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Comm
{
   public class XML
    {
        public static void create(string path)
        {
                XDocument document = new XDocument();
                XElement root = new XElement("Machine");
                XElement book = new XElement("Parameter");
                book.SetElementValue("name", "程序");
                root.Add(book);
                root.Save(path);    
            
        
        }
        static XDocument document = null;
        public static string read(string name, string path)
        {
            // try
            // {
            if (!File.Exists(path)){
                create(path);
            }
           
                //将XML文件加载进来
                document = XDocument.Load(path);
            
                //获取到XML的根元素进行操作
                XElement root = document.Root;
                XElement ele = root.Element("Parameter");
                //获取name标签的值
                XElement shuxing = ele.Element(name);
                 if (shuxing != null)
                {
                    string str = ele.Element(name).Value;
                    return str;
                }
                else
                {
                    return null;

                }
          //  }
          //  catch
          //  {
          //      return null;
          //  } 
        }

        public static void Save(string path)
        {
            document.Save(path);
        }
        public static void write(string name, string value, string path)
        {
             XDocument document=null;
             XElement root = null;
             XElement ele = null;
            // try
            // {
                 document = XDocument.Load(path);
                 root = document.Root;
                 ele = root.Element("Parameter");
                 XElement shuxing = ele.Element(name);
                if (shuxing != null)
                 {
                     ele.Element(name).Value = value;

                 }
                 else
                 {
                     ele.SetElementValue(name, value);
                 }
                document.Save(path);
               
             //}
            // catch
            // {
            // } 
            
        }
    }
}
